/**
 * @name 富文本插件
 * @author gong
 * @todo
 * @description
 *    height = 500, // 高度
      content, // 内容
      disabled = false, // 控制文本框是否可编辑
      uploadUrl // 上传url
 *
 */
import React, { useEffect, useState, useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { plugins, toolbar } from "./plugins";
import { getAuthority } from "@/utils/authority";
import { OSnow } from "@/utils/utils";
import * as _ from "lodash";
import styles from "./index.less";
// 需求描述默认模板
// const DEFAULT_DESC =
//   `1.功能描述：\
//   简要描述要实现的功能。
//   2.范围和用户：&#13;&#10;
//   明确的应用范围和目标用户使得团队有的放矢。\n
//   3.预期效益：\n
//   价值和可量化ROI或提升数字，需要明确的统计公式，如无法统计，则需要提数据埋点需求，通过数据量化收益。`;

// const DEMAND_TEMP =   '<h4>一、功能描述：</h4><span style="color: red">简要描述要实现的功能</span><h4>范围和用户：</h4><span>明确的应用范围和目标用户使得团队有的放矢。</span><h4>预期效益：</h4><span> 价值和可量化ROI或提升数字，需要明确的统计公式，如无法统计，则需要提数据埋点需求，通过数据量化收益。</span> ';

// const STORY_TEMP = 'story模板'

interface TinyEditorProps {
  height?: number;
  content: string;
  disabled?: boolean;
  onContentChange: React.EventHandler<T>;
  placeholder?: string;
  editorKey: string; // todo 暂不知道作用
  maxLength?: number;
  isError?: boolean; // 是否展示错误框
  simToolBar?: string; //自定义工具栏
  onChangePureText?: (s: string) => void; // 获取纯文本
  onEditorBlur?: (str: string) => void;
  paste_as_text?: boolean; // 是否复制为纯文本
}

const { accessToken } = getAuthority("dh-authority") || {};

const winConfig =
  "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';Arial=arial,helvetica,sans-serif;";

const macConfig = "宋体='宋体-简称';黑体='黑体-简';楷体='楷体-简';arial=arial;";

const TextEditor = (props: TinyEditorProps) => {
  const {
    height,
    content,
    disabled,
    editorKey,
    placeholder,
    maxLength,
    isError,
    simToolBar,
    onChangePureText,
    onEditorBlur,
    paste_as_text = false,
  } = props;
  const [isWarning, setIsWarning] = useState(false);
  const [time, setTime] = useState(Date.now());
  const editorRef = useRef(null);
  const cusToolbar = simToolBar || toolbar;
  const pastProps = {
    paste_enable_default_filters: false,
    paste_retain_style_properties: "all",
    paste_word_valid_elements: "*[*]",
    paste_convert_word_fake_lists: false,
    paste_remove_styles_if_webkit: false,
    paste_webkit_styles: "all",
    paste_merge_formats: true,
    paste_data_images: true,
  };

  const handleEditorChange = (content) => {
    const { onContentChange } = props;

    const pureText = tinymce.activeEditor.getContent({ format: "text" });
    onChangePureText && onChangePureText(pureText);
    onContentChange(content);
  };

  const handleUploadImg = (blobInfo, success, failure, progress) => {
    // success("data:" + blobInfo.blob().type + ";base64," + blobInfo.base64());
    // return false
    const file = blobInfo.blob(); // 转化为易于理解的file对象
    // console.log('file:', file)
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.open("POST", "/api/admin/sys_file/uploadIMG");
    xhr.setRequestHeader("token", accessToken);
    xhr.upload.onprogress = function (e) {
      progress((e.loaded / e.total) * 100);
    };
    xhr.onload = function () {
      if (xhr.status < 200 || xhr.status >= 300) {
        failure(`HTTP Error:  ${xhr.status}`);
        return;
      }
      const json = JSON.parse(xhr.responseText);
      console.log(json);
      const { data = {} } = json;
      if (!data || typeof data.url !== "string") {
        failure(`Invalid JSON:  ${xhr.responseText}`);
        return;
      }
      success(data.url);
    };
    xhr.onerror = function () {
      console.log("报错");

      failure(
        `Image upload failed due to a XHR Transport error. Code:  ${xhr.status} `
      );
    };
    const formData = new FormData();
    formData.append("uploadFile", file, file.name);
    formData.append("bucketName", "rich");
    xhr.send(formData);
  };

  const onKeyDown = (e) => {
    // console.log("e", e);
    // const wordcount = tinymce.activeEditor.plugins.wordcount;
    // const tLength = wordcount.body.getWordCount()
    // console.log(maxLength, tLength)
    // if(maxLength && maxLength < tLength) {
    //   const dom = document.getElementsByClassName('tox-tinymce')[0]
    //   const foot = document.getElementsByClassName('tox-statusbar__path-item')[0]
    //   dom.style.borderColor = 'red'
    //   const span = document.createElement('span')
    //   span.innerHTML = `最多输入${maxLength}个字`
    //   span.style.color = 'red'
    //   if(foot.innerHTML.length < 5) {
    //     foot.appendChild(span)
    //   }
    //   setIsWarning(true)
    // } else if(isWarning && maxLength > tLength) {
    //   const dom = document.getElementsByClassName('tox-tinymce')[0]
    //   const foot = document.getElementsByClassName('tox-statusbar__path-item')[0]
    //   dom.style.borderColor = '#D4D7DD'
    //   foot.innerHTML = 'p'
    //   setIsWarning(false)
    // }
    // console.log(wordcount.body.getWordCount());
    // console.log(wordcount.body.getCharacterCount());
    // console.log(wordcount.body.getCharacterCountWithoutSpaces());
  };

  useEffect(() => {
    // console.log("挂载", editorRef.current);
    setTime(Date.now());
    // let target = document.getElementsByClassName('tox-tinymce-aux')[0]
    // if(target) {
    //   while(target.nextElementSibling) {
    //     target = target.nextElementSibling
    //   }
    //   target.parentNode?.appendChild( document.getElementsByClassName('tox-tinymce-aux')[0])
    // }
    return () => {
      // console.log("卸载**************");
    };
  }, [editorKey]);

  useEffect(() => {
    // console.log(
    //   'document.getElementsByClassName("tox-dialog-wrap__backdrop")',
    //   document.getElementsByClassName("tox-dialog-wrap__backdrop")
    // );
  }, [document.getElementsByClassName("tox-dialog-wrap__backdrop")]);

  return (
    <div className={isError && "form_error"}>
      <Editor
        value={content}
        // disabled={disabled}
        // onInit={handleInit}
        // onInit={(evt, editor) => editorRef.current = editor}
        onEditorChange={handleEditorChange}
        // onBeforePaste={onBeforePaste}
        onKeyDown={onKeyDown}
        id={`${editorKey}_${time}`}
        key={`${editorKey}_${time}`}
        init={{
          key: `${editorKey}_${time}`,
          height,
          plugins,
          // placeholder: placeholder || placeholder === "" ? placeholder : DEFAULT_DESC,
          toolbar: cusToolbar,
          language: "zh_CN",
          branding: false, // 隐藏右下角技术支持
          menubar: false,
          // menubar: 'edit',
          ...pastProps,
          file_picker_types: "*",
          relative_urls: false,
          remove_script_host: false,
          content_style: `body { color:#4A5774;font-size:13px;font-family: 黑体 !important } p{margin:0;line-height:1.5}`,
          font_formats: OSnow() === "mac" ? macConfig : winConfig,
          // body_class:"tinymce-style",
          body_id: `${editorKey}_${time}`,
          images_upload_handler: handleUploadImg,
          // paste_preprocess: function(plugin, args) {

          //   console.log(args.content);
          //   args.content = (args.content.replaceAll('楷体', '宋体')) + ' preprocess';
          // }
          setup: (editor) => {
            editor.on("blur", () => {
              const content = editor.getContent();
              onEditorBlur && onEditorBlur(content);
            });
          },
          paste_as_text,
          paste_postprocess: async function (plugin, args) {
            // args.node可以获取到粘贴过来的所有dom节点，直接可以用操作dom的方式取修改它
            // 注意此函数不需要return返回值，直接修改即可
            // console.log("复制粘贴paste_postprocess", args.node);
            // console.log(args.node.childNodes);
            const _recursiceNode = (nodeList: any) => {
              nodeList.forEach((v) => {
                // console.log(v);
                if (paste_as_text) {
                  // 去除换行效果, 这里是配合纯文本配置
                  if (v?.tagName === 'BR') {
                    v.style.display = "none";
                    // console.log(v);
                  }
                }
              });
              Array.from(nodeList).forEach((v) => {
                if (v.childNodes) {
                  _recursiceNode(v.childNodes);
                }
              });
            };
            _recursiceNode(args.node.childNodes);
          },
        }}
      />
    </div>
  );
};

export default TextEditor;
